#!/usr/bin/python
# -*- coding: utf-8 -*-
# https://www.jianshu.com/p/6f7078058023

import os
import sqlite3
import sys
import getopt

rootdir = "./date/"
database = "schedule.db"

def main(argv):
    func = ""
    mode = "insert_scan|insert_today|rs_view"
    try:
        opts, args = getopt.getopt(argv, "hm:", ["help", "mode="])
    except getopt.GetoptError as err:
        print("python schedule.py -m <mode> " + mode +",err:1 ")
        print(err)
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            print("python schedule.py -m <mode> " + mode + ",err:2 ")
            sys.exit()
        elif opt == "-m":
            func = arg
        else:
            print("python schedule.py -m <mode> " + mode + ",err:3")
            sys.exit()
    if func == "insert_today":
        insert_today()
    elif func == "rs_view":
        rs_view()
    elif func == "insert_scan":
        insert_scan()
    else:
        print("python schedule.py -m <mode> " + mode + ",err:3")

def insert_today():
    conn = sqlite3.connect(database)
    c = conn.cursor()
    print "Opened database successfully"

    c.execute("insert into `schedule` (`project_id`, `time`, `type_id`, `site`, `desc`) values (1, date(CURRENT_TIMESTAMP,'localtime'), 3, '', '');")

    conn.commit()
    print "Records created successfully"
    conn.close()

def insert_scan():
    for top, dirs, nondirs in os.walk(rootdir):
        conn = sqlite3.connect(database)
        c = conn.cursor()
        for item in nondirs:
            # print(item)
            c.execute("select * from schedule where `time` = '" + item + "'")
            result = c.fetchall()
            # print(result)
            if len(result) == 0:
                print("发现未添加日期，正在添加到数据库:" + item)
                c.execute("insert into `schedule` (`project_id`, `time`, `type_id`, `site`, `desc`) values (1, '" + item + "', 3, '', '');")
            else:
                # print("date found")
                pass
        conn.commit()
        conn.close()

def rs_view():
    conn = sqlite3.connect(database)
    c = conn.cursor()
    print "Opened database successfully"

    c.execute("select * from rs_view")

    result = c.fetchall()
    for row in result:
        print(row)


    conn.commit()
    print "fetch successfully"
    conn.close()


if __name__ == "__main__":
    main(sys.argv[1:])
